# encoding:utf-8
from app.forms.user import UserForm, LoginForm, SearchForm
from app.models.base import db
from app.models.user import Employee, Role
from app.utils.account import require_admin
from flask import Blueprint, redirect, render_template, session, url_for, flash, g, abort, request

employee_pages = Blueprint('employee', __name__)

ADMIN_USER = "admin"
ADMIN_PSW = "admin"


@employee_pages.route('/employee/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        if form.username.data == ADMIN_USER and form.password.data == ADMIN_PSW:
            # session 的数据是经过加密后存储在 cookie 里
            session['user'] = ADMIN_USER
            flash("登录成功")
            return redirect(url_for('employee.index'))
    else:
        for error in form.errors:
            flash(error)
    return render_template('login.html', form=form)


@employee_pages.route("/")
@require_admin
def index():
    return render_template('index.html')


@employee_pages.route('/employee/logout', methods=['GET'])
def logout():
    session['user'] = None
    return redirect(url_for('employee.login'))


@employee_pages.route('/employee/add', methods=['GET', 'POST'])
@require_admin
def employee_add():
    """添加员工"""
    form = UserForm()
    roles = Role.query.all()
    form.role_id.choices = [(r.id, r.name) for r in roles]
    if form.validate_on_submit():
        employee = Employee()
        form.populate_obj(employee)
        db.session.add(employee)
        db.session.commit()
        flash("添加成功")
        return redirect(url_for('employee.employee_list'))
    else:
        for error in form.errors:
            flash(error)
    return render_template('employee_edit.html',
                           form=form, name=session.get('name'),
                           known=session.get('known', False),
                           )


@employee_pages.route('/employees', methods=['GET', 'POST'])
@require_admin
def employee_list():
    """员工列表"""
    form = SearchForm()
    employees = Employee.query.all()
    if request.method == 'POST':
        keyword = request.form.get("keyword")
        keyword = form.keyword.data
        employees = Employee.query.filter(Employee.name.like("%"+keyword+"%"))
    return render_template('employee_list.html', form=form, employees=employees)


@employee_pages.route('/employee/edit/<employee_id>', methods=['GET', 'POST'])
@require_admin
def employee_edit(employee_id):
    """编辑员工"""
    employee = Employee.query.get(employee_id)
    if not employee:
        abort(404)
    form = UserForm(obj=employee)
    roles = Role.query.all()
    form.role_id.choices = [(r.id, r.name) for r in roles]
    if form.validate_on_submit():
        # form.populate_obj(employee)
        employee.name = form.name.data
        employee.phone = form.phone.data
        employee.email = form.email.data
        employee.role_id = form.role_id.data
        employee.is_locked = form.is_locked.data
        db.session.add(employee)
        db.session.commit()
        flash(u"更新成功")
        return redirect(url_for('employee.employee_list'))
    else:
        for error in form.errors:
            flash(error)
    return render_template('employee_edit.html',
                           form=form, name=session.get('name'),
                           known=session.get('known', False),
                           )


@employee_pages.route('/employee/delete/<employee_id>', methods=['GET'])
@require_admin
def employee_delete(employee_id):
    """删除员工"""
    employee = Employee.query.filter(Employee.id == employee_id).first()

    if not employee:
        abort(404)
    db.session.delete(employee)
    db.session.commit()
    flash(u"删除成功")
    return redirect(url_for('employee.employee_list'))
